package com.tenebrous.jestic.compents.interceptor;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SecurityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap();
        String token = request.getHeader("token");
        String sessionid = request.getSession().getId();
        Object ouser = request.getSession().getAttribute(sessionid);
        log.debug("token：" + token);

        if (ouser != null) {
            return true;
        } else {
            map.put("status", 403);
            map.put("message", "请求失败，凭证无效。");
        }
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSONObject.toJSONString(map));
        printWriter.flush();
        printWriter.close();
        return false;
    }
}
